package com.service.calculate.vehicle;

import java.util.ArrayList;
import java.util.List;

import com.service.bean.signal.GpsSignal;
import com.service.bean.signal.GpsSignalWorkSpeed;
import com.service.cache.CacheManager;

/**
 * 累积车速计算</br>
 * 如果车速为0，不计算；如果车速为3，拆分成speed=1,speed=2,speed=3 三条记录插入数据库
 * @author lj
 * Created on 2015年6月9日
 */
public class SpeedCalculator {
	/**
	 * 当前gps信号
	 */
	private GpsSignal gpsSignal;
	
	public SpeedCalculator(GpsSignal gpsSignal) {
		this.gpsSignal = gpsSignal;
	}
	
	public List<GpsSignalWorkSpeed> speedCalculator() {
		// 将一条GpsSignal拆分成count条数据
		int count = (int) Math.floor(gpsSignal.speed);
		List<GpsSignalWorkSpeed> list = makeSpeed(count);
		if (list==null || list.size()==0) {
			return null;
		}
		String equipmentId = gpsSignal.equipmentId;
		GpsSignalWorkSpeed lastWorkSpeed = null;
		List<GpsSignalWorkSpeed> temporary = new ArrayList<GpsSignalWorkSpeed>();
		for (GpsSignalWorkSpeed workSpeed : list) {
			lastWorkSpeed = CacheManager.instance().getWorkSpeed(equipmentId, workSpeed.speed);
			if (lastWorkSpeed != null) {
				workSpeed.startTime = lastWorkSpeed.startTime;
				workSpeed.keepTime = (workSpeed.gpsTime.getTime() - lastWorkSpeed.gpsTime.getTime())/1000;
			} else {
				workSpeed.startTime = gpsSignal.gpsTime;
				workSpeed.keepTime = 0;
			}
			temporary.add(workSpeed);
		}
		CacheManager.instance().workSpeedMap.put(equipmentId, temporary);
		return list;
	}

	private List<GpsSignalWorkSpeed> makeSpeed(int count) {
		if (count == 0) {
			return null;
		}
		List<GpsSignalWorkSpeed> list = new ArrayList<GpsSignalWorkSpeed>();
		GpsSignalWorkSpeed speed = null;
		for (int i=0; i<count; i++) {
			speed = new GpsSignalWorkSpeed();
			speed.signalId = gpsSignal.signalId;
			speed.gpsTime = gpsSignal.gpsTime;
			speed.equipmentId = gpsSignal.equipmentId;
			speed.speed = i+1;
			speed.address = gpsSignal.baiduLocation;
			speed.maxSpeed = gpsSignal.speed;
			list.add(speed);
		}
		return list;
	}
	
}
